<script lang="ts" setup>
import {
  pageOfTemplateTypeApi,
  pageOfTemplateApi,
  saveOrUpdateTemplateApi,
  delActivityTemplateApi,
} from "@/api/activity";
import QrcodeVue from "qrcode.vue";
import exportData from "@/components/exportData/exportData.vue";

const router = useRouter(),
  store = useStore();
const showExportData = ref(false);
const searchForm = ref<any>({
    labelIds: [],
    type: "",
    subType: "",
    showCount: 30,
    currentPage: 1,
  }),
  loadFinish = ref(false),
  selectLabel = ref<Array<any>>([]),
  activityList = ref<Array<any>>([]),
  classifyList = ref<Array<any>>([]),
  totalSize = ref<number | undefined>(undefined),
  loading = ref(false),
  complete = ref(false),
  autoSearchInd = ref(),
  layoutSpan = ref(6);

const previewPath = `${
  (window as any).VUE_APP_URL[import.meta.env.MODE].activePreviewPath
}${store.state.user.merchant.merchantCode}#/activity/preview/`;

const getPreviewPath = (item: {id: number}) => {
  return `${previewPath}${item.id}?type=custom`
}

const merchantId = store.state.user.merchantId;

const changeSearch = () => {
  if (autoSearchInd.value) {
    clearTimeout(autoSearchInd.value);
  }
  autoSearchInd.value = setTimeout(() => {
    search(true);
  }, 500);
};

const search = async (refresh: boolean = false) => {
  loading.value = true;
  if (refresh) {
    searchForm.value.currentPage = 1;
    activityList.value = [];
  }
  // [或]且[或]
  const rs = await pageOfTemplateApi({
    ...searchForm.value,
    typeIds: searchForm.value.activityTemplateTypeId
      ? [searchForm.value.activityTemplateTypeId]
      : [],
  });
  if (rs.code == 200) {
    let page = (rs as any).page;
    if (page.currentPage >= page.totalPage) {
      loadFinish.value = true;
    }
    searchForm.value.currentPage = page.currentPage + 1;
    activityList.value = activityList.value.concat(rs.payload || []);
    totalSize.value = page.totalResult;
  }
  loading.value = false;
};

const getClassify = async () => {
  const rs = await pageOfTemplateTypeApi({ currentPage: 1, showCount: -1 });
  if (rs.code == 200) {
    classifyList.value = rs.payload;
  }
};

const createActivity = (id: number) => {
  router.push({
    name: "ActivityAdd",
    params: { id },
    query: { type: "private" },
  });
};

const addTemplate = () => {
  router.push({ name: "ActivityDesignPrivate" });
};

const designTemplate = (id: number | string) => {
  router.push({ name: "ActivityDesignPrivate", params: { id } });
};

const deleteTemplate = (activity: any) => {
  ElMessageBox.confirm(`确认删除活动【${activity.name}】吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const rs = await delActivityTemplateApi({ id: activity.id });
    if (rs.code == 200) {
      ElNotification.success({
        message: "删除成功",
      });
      search(true);
    }
  });
};

const onresize = () => {
  if (document.body.clientWidth <= 1800) layoutSpan.value = 6;
  else layoutSpan.value = 4;
};
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  async () => {
    searchForm.value.activityTemplateTypeId = "";
    getClassify();
    search(true);
  },
  {
    deep: true,
  }
);
onMounted(async () => {
  onresize();
  window.onresize = onresize;

  getClassify();
  await search(true);
  nextTick(() => {
    complete.value = true;
  });
});

onBeforeUnmount(() => {
  window.onresize = null;
});
</script>
<script lang="ts">
export default {
  name: "ActivityTemplate",
};
</script>
<template>
  <el-affix :offset="60" style="width: 100%">
    <div class="content-header">
      <div class="content-title">活动模板</div>
    </div>
  </el-affix>
  <div class="container">
    <div class="search-form">
      <div class="classify-item" style="margin-bottom: 10px">
        <div class="classify-name">模板名称：</div>
        <el-input
          v-model="searchForm.name"
          placeholder="搜索模板名称"
          style="max-width: 300px"
          clearable
          @input="changeSearch"
        />
      </div>
      <div class="classify-item" style="margin-bottom: 10px">
        <div class="classify-name">模板类型：</div>
        <el-select
          v-model="searchForm.activityTemplateTypeId"
          placeholder="请选择"
          @change="changeSearch"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="item in classifyList"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>

      <div class="classify-item" style="margin-bottom: 10px">
        <el-button type="primary" @click="changeSearch">查询</el-button>
        <!-- TODO 加权限 -->
        <el-button type="primary" @click="showExportData = true"
          >导出</el-button
        >
      </div>
    </div>
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      "
    >
      <div>共{{ totalSize }}个模板</div>
      <el-button
        v-has="['2020']"
        type="primary"
        icon="plus"
        @click="addTemplate"
        >新增模板</el-button
      >
    </div>
    <template v-if="complete">
      <div
        class="template-list"
        v-infinite-scroll="search"
        :infinite-scroll-distance="0"
        :infinite-scroll-disabled="loadFinish"
        :infinite-scroll-immediate="false"
        style="min-height: 300px"
      >
        <el-row :gutter="20">
          <el-col
            :span="layoutSpan"
            v-for="item in activityList"
            style="margin-bottom: 10px"
          >
            <el-card class="activity-item">
              <div class="activity-img">
                <div class="activity-img_container">
                  <img :src="item.cover" alt="" />
                  <div class="activity-qrcode">
                    <div class="qrcode-container">
                      <qrcode-vue
                        :value="getPreviewPath(item)"
                        :size="120"
                        level="H"
                      />
                    </div>
                    <div>微信扫码体验活动</div>
                    <div class="footer">
                      <div
                        v-has="['2021']"
                        class="footer-item"
                        @click="designTemplate(item.id)"
                      >
                        <el-icon :size="20"><Edit /></el-icon>
                        <div>编辑</div>
                      </div>
                      <!-- <div class="footer-item" @click="designTemplate(item.id)">
                        <el-icon :size="20"><Brush /></el-icon>
                        <div>界面</div>
                      </div> -->
                      <div
                        v-has="['2023']"
                        class="footer-item"
                        @click="createActivity(item.id)"
                      >
                        <el-icon :size="20"><Plus /></el-icon>
                        <div>创建</div>
                      </div>
                      <div
                        v-has="['2022']"
                        class="footer-item"
                        @click="deleteTemplate(item)"
                      >
                        <el-icon :size="20"><Delete /></el-icon>
                        <div>删除</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="activity-name">{{ item.name }}</div>
            </el-card>
          </el-col>
        </el-row>
        <el-empty v-if="activityList.length == 0" description="暂无模板" />
      </div>
    </template>
  </div>
  <exportData
    v-model:show-dialog="showExportData"
    :search-data="searchForm"
    title="活动模板"
    export-type="customTemplateExport"
  >
  </exportData>
</template>
<style lang="scss" scoped>
.content-header {
  padding-left: 30px;
  box-sizing: border-box;
  margin-bottom: 20px;
  height: 68px;
  line-height: 68px;
  font-size: 20px;
  background: #fff;
  display: flex;
  align-items: center;
  box-shadow: 0px 1px 12px 0px rgba(0, 0, 0, 0.06),
    inset 0px -1px 0px 0px #ebedf0;
  .content-title {
    font-weight: 700;
    color: #303133;
  }
}
.container {
  margin: 20px;
  background-color: #fff;
  padding: 20px;
  box-shadow: 0px 1px 12px 0px rgb(0 0 0 / 6%), inset 0px -1px 0px 0px #ebedf0;
}
.search-form {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  .classify-item {
    margin-right: 20px;
    display: flex;
    font-size: 14px;
    align-items: baseline;
    .classify-name {
      width: 80px;
      flex-shrink: 0;
      color: #999999;
    }
    .label-list {
      display: inline-flex;
      flex: 1;
      align-items: center;
      flex-wrap: wrap;
      .label-item {
        text-align: center;
        line-height: 30px;
        margin: 10px 0;
        padding: 0 10px;
        cursor: pointer;
        &.active {
          background-color: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
          border-radius: 4px;
        }
      }
      .el-tag {
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }
  }
}
.template-list {
  // overflow-y: auto;
}

.activity-item {
  :deep(.el-card__body) {
    padding: 0;
  }
  .activity-img {
    position: relative;
    overflow: hidden;
    height: 0;
    padding-bottom: 130%;
    cursor: pointer;
    &_container {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      > img {
        display: block;
        width: 100%;
      }
      .activity-qrcode {
        position: absolute;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        top: 100%;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #000000, $alpha: 0.6);
        color: #ffffff;
        transition: top 0.3s ease-out;
        .qrcode-container {
          background-color: #ffffff;
          padding: 5px;
          border-radius: 4px;
          margin-bottom: 10px;
        }
        .footer {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          .footer-item {
            color: #ffffff;
            cursor: pointer;
            text-align: center;
            font-size: 14px;
            padding: 10px;
          }
        }
      }
    }

    &:hover {
      .activity-qrcode {
        top: 0;
      }
    }
  }
  .activity-name {
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 10px 20px;
    text-align: center;
    font-size: 14px;
  }
}

.pagination {
  :deep(.el-pagination) {
    justify-content: flex-end;
  }
}
</style>
